{                                   
Function:      _LinearRegFaster 

Description:    Replaces TS built-in function LinearRegFC with significantly faster algorithm.

Author:         MarkSanDiego

Updated:        11/03/12    original version

Usage:

	Value1 = _LinearRegFaster(Price, Length, TgtBar, oLRSlope, oLRAngle, oLRIntercept, oLRValueRaw)
	
}


inputs: 
    Price( Numericseries ), 
    Length( Numericsimple ),     	{ Length > 1 }
    TgtBar( Numericsimple ),     	{ use negative integer for future, positive for past }
    oLRSlope( Numericref ), 
    oLRAngle( Numericref ), 
    oLRIntercept( Numericref ), 	{ left intercept, at vertical through Price[ Length - 1 ] }
    oLRValueRaw( Numericref ) ;
 
variables: 
    LastLength( 0 ),
    double SumXY( 0 ), 
    double SumY( 0 ), 
    SumX( 0 ), 
    SumXSqr( 0 ), 
    Divisor( 0 );

if Length > 1 then begin 
    
    If Length <> LastLength then begin
    
        SumX = Length * (Length - 1) * .5; 
        SumXSqr = Length * (Length - 1) * (2 * Length - 1) / 6; 
        Divisor = Square(SumX) - Length * SumXSqr;
        
        SumXY = 0;
        for Value1 = 0 to Length - 1 begin
            SumXY = SumXY + Value1 * Price[Value1] ;
        end ;        
        SumY = Summation(Price, Length);
        
    End else begin
    
        SumY = SumY + Price - Price[Length];    
        SumXY = SumXY + (SumY - Price) - (Length - 1) * Price[Length];
        
    end;    
    
    oLRSlope = ( Length * SumXY - SumX * SumY) / Divisor ;
    oLRAngle = ArcTangent( oLRSlope ) ;
    oLRIntercept = ( SumY - oLRSlope * SumX ) / Length ;
    oLRValueRaw = oLRIntercept + oLRSlope * ( Length - 1 - TgtBar ) ;
    LastLength = Length;
    
    _LinearRegFaster = 1 ;
    
end else
 
    _LinearRegFaster = -1 ;
